import Taro from "@tarojs/taro"

function request(options){
  if(!options.url.startsWith("https://")&&!options.url.startsWith("http://")){
    options.url="https://yuqing.shangyuninfo.com/api"+options.url
  }
  let header={
    "content-type":"application/x-www-form-urlencoded"
  };
  if(options.header){
    header={
      ...header,
      ...options.header
    }

  }
  return new Promise((resolve,reject)=>{
    Taro.request({
      ...options,
      header,
      success(res){
        resolve(res)
      },
      fail(res){
        reject(res);
      }
    })
  })
}
export function get(url,options={}){
  return request({
    url,
    ...options,
  })
}
export function post(url,data,options={}){
  return request({
    url,
    data,
    method:"POST",
    ...options
  })
}
export function downImg(url,name="file",formData={},options={}){
  return new Promise((reslove,reject)=>{
    Taro.chooseImage({
      success :res=> {
        const tempFilePaths = res.tempFilePaths
        Taro.uploadFile({
          url, //仅为示例，非真实的接口地址
          filePath: tempFilePaths[0],
          name,
          formData,
          header:{
            "cookie":Taro.getStorageSync("cookies") || ""
          },
          ...options,
          success :res=>{
            const data =JSON.parse(res.data)
            reslove(data)
          },
          fail(err){
            reject(err)
          }
        })
      }
    })
  })

}
